<template>
  <el-dialog class="gl_dialog_TitleLine" :title="title" :visible.sync="isShow" :close-on-click-modal="false" width="1200px">

    <!-- 顶部过滤 -->
    <el-form ref="addAthleteForm" label-width="80px" :model="qo" @submit.native.prevent>
      <el-row>
        <el-col :span="6">
          <el-form-item label="性别" size="mini">
            <el-select v-model="qo.GenderCode" style="width:100%" size="mini" filterable clearable placeholder="请选择性别" @change="getAthleteList()">
              <el-option v-for="item in dict.dictGender" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="gameInfo.setting.isDisplayMemberInfo">
          <el-form-item label="会员状态" size="mini">
            <el-select v-model="qo.CTAMemberStatusCode" style="width:100%" size="mini" filterable clearable placeholder="请选择会员状态" @change="getAthleteList()">
              <el-option v-for="item in dict.registerMemberStatus" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" size="mini">
            <div style="width:100%" class="gl_clear">
              <div style="width:45%;" class="gl_fl">
                <el-date-picker v-model="qo.BirthdayBegin" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" type="date" placeholder="选择日期" @change="getAthleteList()" />
              </div>
              <div style="width:10%;text-align:center;" class="gl_fl">至</div>
              <div style="width:45%;" class="gl_fl">
                <el-date-picker v-model="qo.BirthdayEnd" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" type="date" placeholder="选择日期" @change="getAthleteList()" />
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="头像" size="mini">
            <el-select v-model="qo.HasPhoto" style="width:100%" size="mini" filterable clearable placeholder="请选择有无头像" @change="getAthleteList()">
              <el-option v-for="item in dictHasPhoto" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="姓名" size="mini">
            <el-input v-model.trim="qo.Filter" clearable placeholder="请输入姓名" @change="getAthleteList()" />
          </el-form-item>
        </el-col>
        <el-col :span="gameInfo.setting.isDisplayMemberInfo?'12':'18'" align="right">
          <el-button type="primary" size="mini" @click="getAthleteList()">搜索</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 运动员表格 -->
    <el-table ref="athleteTable" v-loading="tableLoading" class="gl_mb_15" :data="tableData" size="mini" height="400px" @selection-change="onTableSelectionChange">
      <el-table-column type="selection" width="55" :selectable="selectable" />
      <el-table-column prop="name" label="姓名">
        <template slot-scope="scope">
          <div style="height:68px;display: flex;">
            <img
              class="athlete_face gl_middle gl_mr_10"
              :src="getStaticFileUrl(scope.row.imagePath)"
              alt=""
              @error="onAthleteFaceError"
            >
            <div style="display: flex;flex-direction: column;justify-content: center;">
              <span class="gl_middle">{{ scope.row.name }}</span>
              <span v-if="gameInfo.setting.isDisplayMemberInfo && scope.row.ctaMemberId" class="gl_middle gl_15_ellipsis">{{ "会员号:" + scope.row.ctaMemberId?scope.row.ctaMemberId:'' }}</span>
              <span  v-if="gameInfo.setting.isDisplayMemberInfo && scope.row.ctaMemberExipry" class="gl_middle gl_15_ellipsis">{{ "有效期:" + scope.row.ctaMemberExipry?scope.row.ctaMemberExipry.split('T')[0] :"" }}</span>
            </div>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="60" align="center">
        <template slot-scope="scope">{{ genderDictMap[scope.row.genderCode] && genderDictMap[scope.row.genderCode].value }}</template>
      </el-table-column>
      <el-table-column label="出生日期" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.birthDate ? scope.row.birthDate.slice(0, 10) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="手机号码" />
      <el-table-column prop="idCardNumber" label="证件号码" />
      <el-table-column v-if="gameInfo.setting.isDisplayMemberInfo"  label="会员状态"  prop="ctaMemberStatusCode">
        <template slot-scope="scope">{{ memberStatusDictMap[scope.row.ctaMemberStatusCode] && memberStatusDictMap[scope.row.ctaMemberStatusCode].value }}</template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" width="140">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="clickEditAthlete(scope.row, scope.$index)">{{ $t('button.edit') }}</el-button>
            <!-- <el-button type="text" size="mini" @click="edit(row, 'edit')">编辑</el-button> -->
            <el-button v-if="gameInfo.setting.isDisplayMemberInfo" type="text" size="mini" @click="updatamember(scope.row)">
              <span>更新会员</span>
            </el-button>
          </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <div v-if="isShow" align="center" class="gl_py_10">
      <el-pagination
        :current-page="qo.Page"
        :page-size="qo.maxResultCount"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </div>

    <!-- 底部功能按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="close">{{ $t('button.cancel') }}</el-button>
      <el-button size="mini" type="primary" @click="submitSelectTable">{{ $t('button.submit') }}</el-button>
    </div>

    <!-- 编辑模态框 -->
    <el-dialog class="gl_dialog_TitleLine" title="编辑" append-to-body :visible.sync="dialogVisibleForPersonal" :close-on-click-modal="false" width="1200px">
      <div v-loading="dialogVisibleForPersonalLoading" class="gl_px_10">
        <personal-info ref="refPersonalInfo" :user-data="athleteVO" :is-default-check="athleteVO.isApproved" />
        <div slot="footer" align="right">
          <el-button size="mini" @click="dialogVisibleForPersonal = false">{{ $t('button.cancel') }}</el-button>
          <el-button size="mini" type="primary" @click="submitPersonalInfo">{{ $t('button.submit') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { CopyData } from '@/lib';
import { mapState, mapActions } from 'vuex';
import { deepCopy } from '@/lib';

import defaultFace from '@/assets/images/face_default.png';

import personalInfo from '@/components/PersonalInfo';

import {
  api_GET_EventsManagementRegisterId,
  api_PUT_EventsManagementRegisterId,
  api_POST_EventsManagementRegisterSynregisterCatinfo,
  api_GET_EventsManagementEntryDelegationCandidatesForEntry // 查询注册列表
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementCreateRegisterWithTagsInput,
  Api_GET_EventsManagementEntryDelegationCandidatesForEntryQO // 查询注册列表
} from '@/lib/form/game/swaggerForm';

export default {
  components: {
    personalInfo
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    const _qo = new Api_GET_EventsManagementEntryDelegationCandidatesForEntryQO();
    _qo.HasPhoto = '';
    return {
      isShow: false,
      dictHasPhoto: [
        { code: true, value: '有' },
        { code: false, value: '无' }
      ],
      qo: _qo,
      sourceTableData: [],
      tableData: [],
      total: 0,
      selectionTable: [],
      tableLoading: false,
      defaultFace: defaultFace,
      athleteVO: new SiSTKWEventsManagementCreateRegisterWithTagsInput(),
      dialogVisibleForPersonal: false, // 是否显示编辑运动员信息模态框
      dialogVisibleForPersonalLoading: false // 编辑运动员信息Loading
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    }),
    genderDictMap() {
      const _returnData = {};
      this.dict.gender.forEach(item => {
        _returnData[item.code] = item;
      });
      return _returnData;
    },
    memberStatusDictMap() {
      const _returnData = {};
      this.dict.registerMemberStatus.forEach(item => {
        _returnData[item.code] = item;
      });
      return _returnData;
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        this.qo.CompetitionId = this.gameInfo.id;
        this.qo.DelegationId = this.requiredIdData.delegationId;
        this.getAthleteList();
      } else {
        const _qo = new Api_GET_EventsManagementEntryDelegationCandidatesForEntryQO();
        _qo.HasPhoto = '';
        this.qo = _qo;
      }
    }
  },
  created() {
    this.getDict();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    open () {
      this.isShow = true;
    },
    close () {
      this.$refs.athleteTable.clearSelection();
      this.isShow = false;
    },
    // 获取运动员列表
    getAthleteList (page) {
      this.tableLoading = true;
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      api_GET_EventsManagementEntryDelegationCandidatesForEntry(this.qo)
        .then(
          res => {
            this.tableLoading = false;
            this.sourceTableData = deepCopy(res.items);
            this.tableData = res.items;
            this.total = res.totalCount;
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `报项列表获取失败！ ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 筛选是否满足条件
    selectable(row,index) {
      if(row.ctaMemberStatusCode !== 'Normal' && this.gameInfo.setting.isEntryMemberRule) {
        return false
      } else {
        return true
      }

    },
    onTableSelectionChange (data) {
      this.selectionTable = data;
    },
    // 确认选择表格
    submitSelectTable () {
      if (this.selectionTable.length) {
        this.$emit('onSubmitAthlete', this.selectionTable);
      }
      this.close();
    },
    // 点击编辑运动员
    clickEditAthlete (row, index) {
      this.currentAthleteIndex = index;
      this.getAthleteInfo(row.id);
    },
    // 获取运动员信息
    getAthleteInfo (athleteId) {
      this.dialogVisibleForPersonal = true;
      this.dialogVisibleForPersonalLoading = true;
      api_GET_EventsManagementRegisterId(athleteId)
        .then(
          res => {
            this.dialogVisibleForPersonalLoading = false;
            this.athleteInfo = res;
            CopyData(res, this.athleteVO);
          })
        .catch(
          error => {
            this.dialogVisibleForPersonalLoading = false;
            this.$message({ type: 'error', message: (error.error && error.error.message || '获取运动员信息失败') });
          }
        );
    },
    // 确定修改运动员信息
    submitPersonalInfo () {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            this.updatePersonalInfo(res);
          }
        );
    },
    updatamember(row) {
      this.tableLoading = true;
      api_POST_EventsManagementRegisterSynregisterCatinfo(row.id)
        .then(
          (res) => {
            this.$message({ type: 'success', message: '更新成功' });
            this.getAthleteList(this.qo.Page);
          },
          error => {
            this.tableLoading = false;
            this.$message({ type: 'error', message: `修改用户信息失败 ${error.error.message}` });
          }
        );
    },
    // 更新运动员信息
    updatePersonalInfo (res) {
      this.dialogVisibleForPersonalLoading = true;
      CopyData(res, this.athleteVO);
      this.athleteVO.isCurrentUser = false;
      this.athleteVO.joinCurrentDelegation = true;
      api_PUT_EventsManagementRegisterId(this.athleteInfo.id, this.athleteVO)
        .then(
          (res) => {
            console.log('res: ', res);
            this.dialogVisibleForPersonalLoading = false;
            this.dialogVisibleForPersonal = false;
            this.$message({ type: 'success', message: '操作成功' });
            this.getAthleteList(this.qo.Page);
          },
          error => {
            this.dialogVisibleForPersonalLoading = false;
            this.$message({ type: 'error', message: `修改用户信息失败 ${error.error.message}` });
          }
        );
    },
    // 图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    onAthleteFaceError () {
      const img = event.srcElement;
      img.src = this.defaultFace;
      img.onerror = null;
    },
    // 分页处理
    sizeChange(MaxResultCount) {
      this.qo.MaxResultCount = MaxResultCount;
      this.getAthleteList();
    },
    pageIndexChange(currentPage) {
      this.getAthleteList(currentPage);
    }
  }
};
</script>

<style>
  .athlete_face {
    width: 50px;
    height: 68px;
  }
</style>
